package com.kfm.web.dao;

import com.kfm.web.util.DBHelper;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;

public class UserDao {
    private DBHelper db= new DBHelper();
    public int registDate(String username, String password, String create_time, String email) {
        String hashedPassword = hashPassword(password); // 对密码进行哈希加密

        String sql = "insert into sys_user (user_name, password, create_time, email) values (?, ?, ?, ?)";
        try {
            return db.insert(sql, username, hashedPassword, create_time, email);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public String hashPassword(String password) {
        try {
            // 创建 MessageDigest 实例并指定使用的哈希算法（例如，SHA-256）
            MessageDigest digest = MessageDigest.getInstance("SHA-256");

            // 将密码转换为字节数组并进行哈希计算
            byte[] hashedBytes = digest.digest(password.getBytes());

            // 将哈希结果转换为十六进制字符串
            StringBuilder builder = new StringBuilder();
            for (byte b : hashedBytes) {
                builder.append(String.format("%02x", b));
            }
            return builder.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Failed to hash password", e);
        }
    }
}
